package com.swl.juc.lock;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/*
CountDownLatch 中我们主要用到两个方法一个是 await() 方法，调用这个方法的线程会被阻塞，
另外一个是 countDown() 方法，调用这个方法会使计数器减一，当计数器的值为 0 时，因调用 await() 方法被阻塞的线程会被唤醒，继续执行。
 */
public class CountDownLatchTest {

    public static void main(String[] args) {
        System.out.println("主要线程开始等待其他子线程执行");
        test();
    }

    public static void test() {
        int threadCount = 5;
        CountDownLatch countDownLatch = 
                new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int finalI = i + 1;
            new Thread(() -> {
                System.out.println("第 " + finalI + " 线程开始");
                Random random = new Random();
                try {
                    Thread.sleep(random.nextInt(10000) + 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第 " + finalI + " 线程执行完毕");

                countDownLatch.countDown();
            }).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(threadCount + " 个线程全部执行完毕");
        System.out.println("主线程继续执行");
        //todo业务代码
    }
}
